import { DeviceLedger } from '@/api/interface/device/ledger';
import { customTable } from '@/components/ProTable/interface';
import { ProTableValue } from '@/interface/public';

/**
 * @name 设备台账
 */
export function useDeviceData(deviceDataRef: ProTableValue, proTableBox?: ProTableValue) {
  let deviceData = reactive<customTable>({
    visible: false,
    initParam: {
      id: '',
      flagUse: '0',
      status: 1
    },
    // 表格配置项
    columns: [
      { prop: 'operation', label: 'operation', fixed: 'left', width: 80 },
      {
        label: '设备编号',
        prop: 'code',
        search: {
          key: 'key',
          el: 'input',
          label: '关键字',
          display: false
        }
      },
      {
        label: '工序',
        prop: '_process'
      },
      {
        label: '设备名称',
        prop: 'name',
        width: 280
      },
      {
        label: '类型',
        prop: 'type'
      },
      {
        label: '设备型号',
        prop: 'model'
      },
      {
        label: '规格',
        prop: 'size'
      },
      {
        label: '单位',
        prop: 'unit'
      },
      {
        label: '备注',
        prop: 'remark'
      }
    ],
    headButtonList: [],
    rowButtonList: [
      {
        label: '选择',
        type: 'primary',
        attrs: {
          link: true
        },
        methods: (row: DeviceLedger.ResSearchProp) => {
          selectDevice(row);
        }
      }
    ]
  });

  /**
   * @description: 打开设备选择弹框
   * @return {*}
   */
  const openDeviceBox = () => {
    deviceData.visible = true;
    nextTick(() => {
      deviceDataRef.value?.getTableList();
    });
  };

  const deviceCallBack = (data: DeviceLedger.ResSearch) => {
    data.records = data.records.map(item => {
      const { line, process } = item;
      return {
        ...item,
        _process: `${process} / ${line}`
      };
    });
    return data;
  };

  /**
   * @description: 选择设备
   * @return {*}
   */
  const selectDevice = (row: DeviceLedger.ResSearchProp, db?: Function) => {
    if (proTableBox?.value) {
      const device = proTableBox.value?.tableData.find((item: any) => item.isAddFlag || item['edit']);
      device.deviceId = row.id;
      const { code, deviceInfo, line, process } = row;
      device.deviceInfo = `${process} / ${line} ${code} - ${deviceInfo}`;
      deviceData.visible = false;
    }
    db && db(row);
  };

  return {
    deviceData,

    openDeviceBox,
    selectDevice,
    deviceCallBack
  };
}
